package Railroad.Communication.Network;

import Railroad.Communication.CommData;
import Railroad.Communication.CommDriver;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

public class CommDriverNetwork implements CommDriver {
    private static final int port = 80;
    private static final String host = "localhost";
    
    private Socket socket = null;
    private DataInputStream dataIn = null;
    private DataOutputStream dataOut = null;

    @Override
    public boolean connect() {
        try {
            socket = new Socket(host, port);
            dataIn = new DataInputStream(socket.getInputStream());
            dataOut = new DataOutputStream(socket.getOutputStream());
            return true;
        } catch (IOException ex) {
            // could not connect
            return false;
        }
    }

    @Override
    public void disconnect() {
        if (isConnected()) {
            try {
                socket.close();
            }
            catch (IOException ex) {
            }
        }
    }

    @Override
    public boolean isConnected() {
        return socket != null;
    }

    @Override
    public void send(CommData data) {
        try {
            dataOut.write(data.toArray());
        } catch (IOException ex) {
        }
    }

    @Override
    public CommData receive(int length) {
        try {
            byte[] data = new byte[length];
            dataIn.read(data, 0, length);
            return new CommData(data);
        } catch (IOException ex) {
            return null;
        }
    }
    
}
